package cn.iocoder.yudao.module.contract.controller.admin.frameworkAgreement;

import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants;
import cn.iocoder.yudao.module.contract.controller.admin.orderContract.vo.OrderContractSaveReqVO;
import cn.iocoder.yudao.module.contract.dal.dataobject.order.OrderDO;
import cn.iocoder.yudao.module.contract.dal.dataobject.orderContract.OrderContractDO;
import cn.iocoder.yudao.module.contract.utils.FileDownloadUtil;
import cn.iocoder.yudao.module.contract.utils.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.v3.oas.annotations.Parameters;
import org.checkerframework.checker.units.qual.C;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.*;
import javax.servlet.http.*;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import java.io.IOException;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import static cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants.NOT_IMPLEMENTED;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.error;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;

import cn.iocoder.yudao.module.contract.controller.admin.frameworkAgreement.vo.*;
import cn.iocoder.yudao.module.contract.dal.dataobject.frameworkAgreement.FrameworkAgreementDO;
import cn.iocoder.yudao.module.contract.service.frameworkAgreement.FrameworkAgreementService;
import org.springframework.web.multipart.MultipartFile;

@Tag(name = "管理后台 - 框架协议")
@RestController
@RequestMapping("/contract/framework-agreement")
@Validated
public class FrameworkAgreementController {

    @Resource
    private FrameworkAgreementService frameworkAgreementService;

    @PostMapping("/create")
    @Operation(summary = "创建框架协议")
    @PreAuthorize("@ss.hasPermission('contract:framework-agreement:create')")
    public CommonResult<Long> createFrameworkAgreement(@Valid @RequestBody FrameworkAgreementSaveReqVO createReqVO) {
        return success(frameworkAgreementService.createFrameworkAgreement(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新框架协议")
    @PreAuthorize("@ss.hasPermission('contract:framework-agreement:update')")
    public CommonResult<Boolean> updateFrameworkAgreement(@Valid @RequestBody FrameworkAgreementSaveReqVO updateReqVO) {
        frameworkAgreementService.updateFrameworkAgreement(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除框架协议")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('contract:framework-agreement:delete')")
    public CommonResult<Boolean> deleteFrameworkAgreement(@RequestParam("id") Long id) {
        frameworkAgreementService.deleteFrameworkAgreement(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得框架协议")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('contract:framework-agreement:query')")
    public CommonResult<FrameworkAgreementRespVO> getFrameworkAgreement(@RequestParam("id") Long id) {
        FrameworkAgreementDO frameworkAgreement = frameworkAgreementService.getFrameworkAgreement(id);
        return success(BeanUtils.toBean(frameworkAgreement, FrameworkAgreementRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得框架协议分页")
    @PreAuthorize("@ss.hasPermission('contract:framework-agreement:query')")
    public CommonResult<PageResult<FrameworkAgreementRespVO>> getFrameworkAgreementPage(@Valid FrameworkAgreementPageReqVO pageReqVO) {
        PageResult<FrameworkAgreementRespVO> pageResult = frameworkAgreementService.getFrameworkAgreementPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, FrameworkAgreementRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出框架协议 Excel")
    @PreAuthorize("@ss.hasPermission('contract:framework-agreement:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportFrameworkAgreementExcel(@Valid FrameworkAgreementPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<FrameworkAgreementRespVO> list = frameworkAgreementService.getFrameworkAgreementPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "框架协议.xls", "数据", FrameworkAgreementExportVO.class,
                        BeanUtils.toBean(list, FrameworkAgreementExportVO.class));
    }

    @GetMapping("/get-import-template")
    @Operation(summary = "获得导入用户模板")
    public void importTemplate(HttpServletResponse response) throws IOException {
        // 手动创建导出 demo
        List<FrameworkAgreementImportExcelVO> list = Arrays.asList(
        );
        // 输出
        ExcelUtils.writeExcel(response, "框架协议导入模板.xls", "框架协议", FrameworkAgreementImportExcelVO.class, list);
    }

    @PostMapping("/import")
    @Operation(summary = "导入用户")
    @Parameters({
            @Parameter(name = "file", description = "Excel 文件", required = true),
            @Parameter(name = "updateSupport", description = "是否支持更新，默认为 false", example = "true")
    })
    public CommonResult<FrameworkAgreementImportRespVO> importExcel(@RequestParam("file") MultipartFile file,
                                                                    @RequestParam(value = "updateSupport", required = false, defaultValue = "false") Boolean updateSupport) throws Exception {
        List<FrameworkAgreementImportExcelVO> list = ExcelUtils.read(file, FrameworkAgreementImportExcelVO.class);
        return success(frameworkAgreementService.importList(list, updateSupport));
    }


    /**
     * 本地资源通用下载
     */
    @GetMapping("/download")
    public ResponseEntity<?> download(String ids) throws UnsupportedEncodingException {
        String[] id = ids.split(",");
        if(id.length==1){
            //单文件下载
            FrameworkAgreementDO agreement = frameworkAgreementService.getById(id[0]);
            agreement.setDownloadCount(agreement.getDownloadCount()+1);
            frameworkAgreementService.updateById(agreement);
            String fileName = agreement.getClientCode()+agreement.getClientName()+agreement.getContractNo()+agreement.getCompanyPersonName();
            return FileDownloadUtil.downloadFile(agreement.getContractFileUrl(), URLEncoder.encode(fileName, "UTF-8"));
        }else if(id.length>1){
            //批量下载
            List<FrameworkAgreementDO> list = frameworkAgreementService.list(Wrappers.<FrameworkAgreementDO>lambdaQuery().in(FrameworkAgreementDO::getId,id));
            List<String> fileUrls = new ArrayList<>();
            List<String> fileNames = new ArrayList<>();
            for(FrameworkAgreementDO agreement: list){
                fileUrls.add(agreement.getContractFileUrl());
                String fileName = agreement.getClientCode()+agreement.getClientName()+agreement.getContractNo()+agreement.getCompanyPersonName();
                fileNames.add(fileName);
                agreement.setDownloadCount(agreement.getDownloadCount()+1);
                frameworkAgreementService.updateById(agreement);
            }
            return FileDownloadUtil.downloadZip(fileUrls,fileNames);
        }else {
            throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(),"请选择要下载的合同");

        }
    }
    /**
     * 合同打印计数
     */
    @GetMapping("/prints")
    public CommonResult<?> prints(String ids){
        String[] id = ids.split(",");
        if(id.length!=0){
            frameworkAgreementService.update(Wrappers.<FrameworkAgreementDO>update().setSql(" print_count = print_count + 1").in("id",id));
            return success("操作成功");
        }else {
            return CommonResult.error(NOT_IMPLEMENTED);
        }
    }


    @PutMapping("/fileUpload")
    @Operation(summary = "合同上传")
    public CommonResult<Boolean> fileUpload(@Valid @RequestBody FrameworkAgreementSaveReqVO updateReqVO) {
//        if (StringUtils.isBlank(updateReqVO.getFileIds())) {
//            return error("请上传文件");
//        }
        FrameworkAgreementDO updateObj = BeanUtils.toBean(updateReqVO, FrameworkAgreementDO.class);
        frameworkAgreementService.updateById(updateObj);
        return success(true);
    }
}